package com.gp.service.impl;

import com.gp.dao.BaseAreaDao;
import com.gp.entity.BaseArea;
import com.gp.service.BaseAreaService;
import com.gp.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BaseAreaServiceImpl implements BaseAreaService {
    @Autowired
    private BaseAreaDao baseAreaDao;
    @Override
    public CommonResult findAll() {
        List<BaseArea> baseAreas = baseAreaDao.selectList(null);
        List<BaseArea> provinces=new ArrayList<>();
        //1.查询省
        for (BaseArea baseArea:baseAreas){
             if(baseArea.getParentid()==0){
                   provinces.add(baseArea);
             }
        }

        //2.查询对应的子菜单
        for(BaseArea baseArea:provinces){
            List<BaseArea> children = findChildren(baseAreas, baseArea.getBaseAreaid());
            if(children.size()>0) {
                baseArea.setChildren(children);
            }
        }
        return new CommonResult(2000,"查询成功",provinces);
    }

    public List<BaseArea> findChildren(List<BaseArea> list,Integer pid){
           List<BaseArea> children=new ArrayList<>();
           for(BaseArea baseArea:list){
                 if(baseArea.getParentid().equals(pid)){
                       children.add(baseArea);
                 }
           }
           for(BaseArea baseArea:children){
               List<BaseArea> children1 = findChildren(list, baseArea.getBaseAreaid());
               if(children1.size()>0) {
                   baseArea.setChildren(children1);
               }
           }
           return children;

    }
}
